<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2019 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2019-06-03
 * Time: 10:28
 */

namespace App\Library\Mall\Shop;


use App\Models\Shop;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait ShopSubscribeManagers
{

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $shop_id = $request->input('shop_id', 0);
        $subscribe = Auth::user()->subscribedShops()->where('shop_id', $shop_id)->firstOrCreate(['shop_id'=>$shop_id]);
        return ajaxReturn(['subscribe'=>$subscribe]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request){
        $id = $request->input('id', 0);
        Auth::user()->subscribedShops()->where('id', $id)->delete();
        return ajaxReturn();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Relations\HasMany|mixed
     */
    protected function batchgetSubscribedShops(Request $request){
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 20);
        $q = $request->input('q');

        $items = Auth::user()->subscribedShops()->with('shop')->when($q, function (Builder $builder) use ($q){
            return $builder->whereHas('shop', function (Builder $builder) use ($q){
                return $builder->where('shop_name', 'LIKE', "%$q%");
            });
        })->offset($offset)->take($count)->get();

        return $items;
    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    protected function batchgetSubscribedUsers(Request $request){
        $shop_id = $request->input('shop_id');
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 20);
        $q = $request->input('q');

        $shop = Shop::find($shop_id);
        if ($shop){
            $items = $shop->fans()->with('user')->when($q, function (Builder $builder) use ($q){
                return $builder->whereHas('user', function (Builder $builder) use ($q){
                    return $builder->where('username', 'LIKE', "%$q%");
                });
            })->offset($offset)->take($count)->get();
        } else {
            $items = [];
        }

        return $items;
    }
}
